package com.cw.jeeyt.service.impl.system;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.cw.jeeyt.common.StringTools;
import com.cw.jeeyt.common.UUIDTool;
import com.cw.jeeyt.common.utils.StringUtils;
import com.cw.jeeyt.service.bo.system.SystemAttachBo;
import com.cw.jeeyt.service.bo.system.SystemAttachRelationBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.dao.intf.system.SystemAttachDao;
import com.cw.jeeyt.dao.model.system.SystemAttachDo;
import com.cw.jeeyt.service.converter.system.SystemAttachConverter;
import com.cw.jeeyt.service.intf.system.SystemAttachRelationService;
import com.cw.jeeyt.service.intf.system.SystemAttachService;
import com.cw.jeeyt.service.utils.FileTools;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 附件信息业务实现类
 *
 * @author chenw
 * @version 1.0.0
 */
@Service
public class SystemAttachServiceImpl implements SystemAttachService {

    private static final Logger logger = LoggerFactory.getLogger(SystemAttachServiceImpl.class);
    @Autowired
    private SystemAttachDao systemAttachDao;//附件信息数据库操作接口
    @Autowired
    private SystemAttachRelationService systemAttachRelationService;//附件关联关系业务实现接口

    @Override
    public List<SystemAttachBo> getAttachListByObjectId(String objectId) throws Exception {
        if (StringUtils.isEmpty(objectId)) {
            logger.error("objectId为空");
            return null;
        }
        return SystemAttachConverter.doList2BoList(systemAttachDao.getAttachListByObjectId(objectId));
    }

    /**
     * 分页查询附件信息
     *
     * @param systemAttachBo
     * @param startNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<SystemAttachBo> queryByPage(SystemAttachBo systemAttachBo, Integer startNum, Integer pageSize)
    throws Exception {
        PageInfo<SystemAttachDo> pageInfo = systemAttachDao.queryByPage(SystemAttachConverter.bo2Do(systemAttachBo),
            startNum, pageSize);
        return new PageInfo<>(pageInfo, SystemAttachConverter.doList2BoList(pageInfo.getList()));
    }

    /**
     * 根据主键查寻附件信息
     *
     * @param id
     * @return
     */
    @Override
    public SystemAttachBo getSystemAttachById(String id) throws Exception {

        if (StringUtils.isEmpty(id)) {
            logger.error("--主键id为空--");
            return null;
        }

        return SystemAttachConverter.do2Bo(systemAttachDao.getById(id));
    }

    /**
     * 新增附件信息
     *
     * @param systemAttachBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insert(SystemAttachBo systemAttachBo) throws Exception {

        if (systemAttachBo == null) {
            logger.error("附件信息为空");
            return null;
        }
        SystemAttachDo systemAttach = SystemAttachConverter.bo2Do(systemAttachBo);
        systemAttach.setId(UUIDTool.getUUID());
        systemAttach.setCreateBy(SessionUtil.getSessionUserId());
        systemAttach.setCreateDate(new Date());
        systemAttach.setUpdateBy(SessionUtil.getSessionUserId());
        systemAttach.setUpdateDate(new Date());
        return systemAttachDao.insert(systemAttach);
    }

    /**
     * 处理附件信息
     *
     * @param objectId
     * @param fileIds
     * @param deleteIds
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void dealSystemAttach(String objectId, String attachType, String fileIds, String deleteIds)
    throws Exception {
        if (!StringUtils.isEmpty(fileIds)) {
            fileIds = StringTools.removeEndStr(fileIds, ",");
            String[] fileIdList = fileIds.split(",");
            for (String fileId : fileIdList) {
                SystemAttachRelationBo systemAttachRelationBo = new SystemAttachRelationBo();
                systemAttachRelationBo.setId(UUIDTool.getUUID());
                systemAttachRelationBo.setAttachId(fileId);
                systemAttachRelationBo.setObjectId(objectId);
                systemAttachRelationBo.setAttachType(attachType);
                systemAttachRelationBo.setCreateBy(SessionUtil.getSessionUserId());
                systemAttachRelationBo.setCreateDate(new Date());
                systemAttachRelationBo.setUpdateBy(SessionUtil.getSessionUserId());
                systemAttachRelationBo.setUpdateDate(new Date());
                systemAttachRelationService.insert(systemAttachRelationBo);
            }
        }
        if (!StringUtils.isEmpty(deleteIds)) {
            deleteIds = StringTools.removeEndStr(fileIds, ",");
            String[] deleteIdList = deleteIds.split(",");
            for (String deleteId : deleteIdList) {
                SystemAttachDo systemAttach = systemAttachDao.getById(deleteId);
                systemAttachDao.delete(systemAttach);
            }

        }
    }

    /**
     * 更新附件信息
     *
     * @param systemAttachBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(SystemAttachBo systemAttachBo) throws Exception {

        if (systemAttachBo == null) {
            logger.error("附件信息为空");
            return;
        }

        SystemAttachDo systemAttach = SystemAttachConverter.bo2Do(systemAttachBo);
        systemAttach.setUpdateBy(SessionUtil.getSessionUserId());
        systemAttach.setUpdateDate(new Date());

        systemAttachDao.update(systemAttach);
    }

    /**
     * 删除附件信息
     *
     * @param systemAttachBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(SystemAttachBo systemAttachBo) throws Exception {

        if (systemAttachBo == null) {
            logger.error("附件信息为空");
            return;
        }
        systemAttachDao.delete(SystemAttachConverter.bo2Do(systemAttachBo));
    }

    @Override
    public String uploadAttachToDB(Map<String, MultipartFile> fileMap) throws Exception {
        StringBuffer attachIds = new StringBuffer();
        for (Map.Entry<String, MultipartFile> f : fileMap.entrySet()) {
            MultipartFile file = f.getValue();
            String id = UUIDTool.getUUID();
            String originalFileName = file.getOriginalFilename();
            attachIds.append(id + ",");
            SystemAttachDo attach = new SystemAttachDo();
            attach.setId(id);
            attach.setFileName(originalFileName);
            attach.setFileSize(file.getSize());
            attach.setContentType(FileTools.getFileExtentionByOriginalFileName(originalFileName));
            attach.setContent(file.getBytes());
            attach.setFileType("1");
            systemAttachDao.insert(attach);
        }
        return attachIds.toString();
    }

    @Override
    public String uploadAttachToDirectory(Map<String, MultipartFile> fileMap, String path) throws Exception {
        Date currentTime = new Date();
        long prefix = currentTime.getTime();
        StringBuffer attachIds = new StringBuffer();
        for (Map.Entry<String, MultipartFile> f : fileMap.entrySet()) {
            MultipartFile file = f.getValue();
            String originalFileName = prefix + "_" + file.getOriginalFilename();
            File fileDir = new File(path + "upload" + File.separator);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            File files = new File(path + "upload" + File.separator + originalFileName);
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(files);
                fileOutputStream.write(file.getBytes());
                fileOutputStream.flush();
                String id = UUIDTool.getUUID();
                attachIds.append(id + ",");
                SystemAttachDo attachDir = new SystemAttachDo();
                attachDir.setId(id);
                attachDir.setFileName(file.getOriginalFilename());
                attachDir.setFileSize(file.getSize());
                attachDir.setContentType(FileTools.getFileExtentionByOriginalFileName(originalFileName));
                attachDir.setFileDir(path + "upload" + File.separator);
                attachDir.setFileType("2");
                systemAttachDao.insert(attachDir);
            } catch (FileNotFoundException e) {
                logger.error("上传文件到目录" + path + "时发生错误", e);
                e.printStackTrace();
            } catch (IOException e) {
                logger.error("上传文件到目录" + path + "时发生错误", e);
                e.printStackTrace();
            } catch (Exception e) {
                logger.error("上传文件到目录" + path + "时发生错误", e);
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        logger.error("上传文件到目录" + path + "时发生错误", e);
                        e.printStackTrace();
                    }
                }
            }
        }
        return attachIds.toString();
    }

    @Override
    public String uploadAttachToDirectoryAndDb(Map<String, MultipartFile> fileMap, String path) throws Exception {
        Date currentTime = new Date();
        long prefix = currentTime.getTime();
        StringBuffer attachIds = new StringBuffer();
        for (Map.Entry<String, MultipartFile> f : fileMap.entrySet()) {
            MultipartFile file = f.getValue();
            String originalFileName = prefix + "_" + file.getOriginalFilename();
            File fileDir = new File(path + "upload" + File.separator);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            File files = new File(path + "upload" + File.separator + originalFileName);
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(files);
                fileOutputStream.write(file.getBytes());
                fileOutputStream.flush();
                String id = UUIDTool.getUUID();
                attachIds.append(id + ",");
                SystemAttachDo attachDir = new SystemAttachDo();
                attachDir.setId(id);
                attachDir.setFileName(originalFileName);
                attachDir.setOriginalFileName(file.getOriginalFilename());
                attachDir.setFileSize(file.getSize());
                attachDir.setContentType(FileTools.getFileExtentionByOriginalFileName(originalFileName));
                attachDir.setContent(file.getBytes());
                attachDir.setFileDir(path + "upload" + File.separator);
                attachDir.setFileType("3");
                systemAttachDao.insert(attachDir);
            } catch (FileNotFoundException e) {
                logger.error("上传文件到目录" + path + "时发生错误", e);
                e.printStackTrace();
            } catch (IOException e) {
                logger.error("上传文件到目录" + path + "时发生错误", e);
                e.printStackTrace();
            } catch (Exception e) {
                logger.error("上传文件到目录" + path + "时发生错误", e);
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        logger.error("上传文件到目录" + path + "时发生错误", e);
                        e.printStackTrace();
                    }
                }
            }
        }
        return attachIds.toString();
    }

    /**
     * 处理附件信息
     */
    @Override
    public void addAttachRelation(String objectId, String attachType, String fileIds, String deleteIds)
    throws Exception {
        //新增附件关联关系并且删除取消掉的附件信息
        this.dealSystemAttach(objectId, attachType, fileIds, deleteIds);
    }

    /**
     * 删除附件关联关系以及附件信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteAttachRelation(String objectId, String attachId) throws Exception {
        SystemAttachDo systemAttach = systemAttachDao.getById(attachId);
        if (systemAttach != null) {
            systemAttachDao.delete(systemAttach);
            String fileDir = systemAttach.getFileDir();
            String fileName = systemAttach.getFileName();
            File file = new File(fileDir + fileName);
            if (file.exists()) {
                file.delete();
            }
        }
        systemAttachRelationService.deleteByObjectIdAndAttachId(objectId, attachId);
    }
}
